package com.well.rpc.register.ribbon;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractServerList;
import com.well.rpc.config.ClientDataConfig;
import com.well.rpc.model.RegisterModel;

import java.util.ArrayList;
import java.util.List;

public class WdServerList extends AbstractServerList<WdServer> {

    private List<RegisterModel> wdServerList;
    private String serverName;

    public void init(){
        List<RegisterModel> registerModels = ClientDataConfig.getRegisterModels();
        this.wdServerList = registerModels;
    }

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {
        this.serverName = iClientConfig.getClientName();
    }


    @Override
    public List<WdServer> getInitialListOfServers() {
        init();
        return initServerList(wdServerList);
    }

    @Override
    public List<WdServer> getUpdatedListOfServers() {
        init();
        return initServerList(wdServerList);
    }

    public List<WdServer> initServerList(List<RegisterModel> serverModels) {
        List<WdServer> wdServerLists = new ArrayList<>();
        if (serverModels != null) {
            for (int i = 0; i < serverModels.size(); i++) {
                RegisterModel serverModel = serverModels.get(i);
                if(!serverName.equals(serverModel.getServerName())){
                    continue;
                }
                Instance instance = new Instance();
                instance.setClusterName("defaultCluster");
                instance.setIp(serverModel.getServerIp());
                instance.setPort(serverModel.getServerPort());
                instance.setServiceName(serverModel.getGroup() + "@@" + serverModel.getServerName());
                //192.168.31.59#10001#DEFAULT#DEFAULT_GROUP@@service-storage
                instance.setInstanceId(instance.getIp() + "#" + instance.getPort() + "#" + serverModel.getGroup() + "@@" + instance.getServiceName());
                WdServer wdServer = new WdServer(instance);
                wdServerLists.add(wdServer);
            }
        }
        return wdServerLists;
    }
}
